package com.bookstore.dao;

import com.bookstore.utils.JdbcUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public abstract class BaseDao {
    //使用DBUtils操作
    private QueryRunner queryRunner = new QueryRunner();

    //增删改 DML update
    public int update(String sql, Object... params) {
        Connection connection = JdbcUtils.getConnection();
        try {
            int result = queryRunner.update(connection, sql, params);
            return result;
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection);
        }
        return -1;
    }

    /**
     * 查询单个javaBean
     *
     * @param type   返回的对象类型
     * @param sql    查询的sql语句
     * @param params 查询的参数
     * @param <T>    返回类型的泛型
     * @return 查询结果
     */
    public <T> T queryForOne(Class<T> type, String sql, Object... params) {
        Connection connection = JdbcUtils.getConnection();
        try {
            return queryRunner.query(connection, sql, new BeanHandler<T>(type), params);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection);
        }
        return null;
    }

    //查询多个javaBean
    public <T> List<T> queryForList(Class<T> type, String sql, Object... params) {
        Connection connection = JdbcUtils.getConnection();
        try {
            return queryRunner.query(connection, sql, new BeanListHandler<T>(type), params);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection);
        }
        return null;
    }

    //单独查询某一行中某一个字段
    public Object queryForSingleValue(String sql, Object... params) {
        Connection connection = JdbcUtils.getConnection();
        try {
            return queryRunner.query(connection, sql, new ScalarHandler(), params);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            JdbcUtils.close(connection);
        }
        return null;
    }

}
